package org.flown.novel.data;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

import com.baomidou.mybatisplus.annotation.*;

import lombok.Data;

@Data
@TableName("chapter")
public class Chapter
{
    public enum Column
    {
        ID("id"),
        BOOK_ID("book_id"),
        TITLE("title"),
        UPLOAD_TIME("upload_time"),
        UPDATE_TIME("update_time");

        private final String name;
        private Column(String name) {this.name = name;}
        public String getName(){return this.name;}
    }

    @TableId(value = "id", type = IdType.AUTO)
    private Integer id = 0;
    private Integer bookId;
    private String title;


    @TableField(fill = FieldFill.INSERT, insertStrategy = FieldStrategy.IGNORED, updateStrategy = FieldStrategy.IGNORED)
    private java.util.Date uploadTime;//自动填充
    @TableField(fill = FieldFill.INSERT_UPDATE, insertStrategy = FieldStrategy.IGNORED, updateStrategy = FieldStrategy.IGNORED)
    private java.util.Date updateTime;//自动更新


    public Chapter(Integer book_id, String title)
    {
        this.bookId = book_id;
        this.title = title;
    }

    public String getChapterRealPath()
    {
        return DirectoryInformation.BOOK.getRealPath() + "/" + this.bookId + "/" + this.id + ".txt";
    }

    public void deleteChapterFile()
    {
        String path = DirectoryInformation.BOOK.getRealPath() + "/" + this.bookId + "/" + this.id + ".txt";
        File file = new File(path);
        file.delete();//它会判断文件存在与否
    }

    public String getChapterContent()
    {
        String path = this.getChapterRealPath();
        try
        {
            return Files.readString(Paths.get(path));
        }
        catch (IOException e) {e.printStackTrace();}
        return null;
    }


    public void setContent(String content)
            throws IOException
    {
        File file = new File(this.getChapterRealPath());

        if (!file.exists())
            file.createNewFile();
        FileWriter writer = new FileWriter(file);
        writer.write(content);
        writer.close();

        //这个content比较特殊，数据库不保存这个，所以手动改一下updateTime，使得可以进行dao.update操作
        this.updateTime = new java.util.Date(System.currentTimeMillis());
    }
}



